<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select v-model="query.depotId" placeholder="请选择倉庫" class="filter-item" @change="crud.toQuery">
          <el-option
            v-for="item in depotList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-input
          v-model="query.blurry"
          clearable
          placeholder="關鍵字查詢"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
          @input="crud.toQuery"
        />
        <el-select
          v-model="query.publishStatus"
          placeholder="是否上架"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.publishStatus"
            :key="item.id"
            :label="item.dictValue"
            :value="item.dictKey"
          />
        </el-select>
        <el-cascader
          ref="cascader"
          v-model="productCategoryId"
          clearable
          class="filter-item"
          placeholder="商品类型搜索"
          :options="productCateOptions"
          style="width: 200px;"
          @keyup.enter.native="setProductCategoryId"
          @change="setProductCategoryId"
        />
        <label class="el-form-item-label" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <template #right>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-upload2"
            :disabled="!crud.selections.length > 0"
            @click="upOrDown(1)"
          >上架
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-download"
            :disabled="!crud.selections.length > 0"
            @click="upOrDown(0)"
          >下架
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-download"
            @click="productExport"
          >导出</el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-download"
            :disabled="!crud.selections.length > 0"
            @click="updateDeliveryVisible = true"
          >批量修改配送</el-button>
        </template>
      </crudOperation>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        style="width: 100%;"
        row-key="id"
        stripe
        :header-cell-style="{'text-align':'center'}"
        @selection-change="crud.selectionChangeHandler"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="pic" label="商品图片">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              width="200"
              trigger="hover"
            >
              <img :src="baseApi + scope.row.pic" style="max-height: 200px">
              <img slot="reference" :src="baseApi + scope.row.pic" style="height: 60px;width: 60px;"></el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="nameCn" label="商品描述" width="300" :show-overflow-tooltip="true" align="left" sortable>
          <template slot-scope="scope">
            <div>中文名称:{{ scope.row.nameCn }}</div>
            <div>英文名称:{{ scope.row.nameEn }}</div>
            <div>upc:{{ scope.row.upc }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="產品編號" sortable />
        <el-table-column prop="productCategoryId" label="商品分類" sortable>
          <template v-if="scope.row.productCategory" slot-scope="scope">
            <div>{{ scope.row.productCategory.nameCn || '' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="brandId" label="品牌名称" sortable>
          <template v-if="scope.row.brand" slot-scope="scope">
            <div>{{ scope.row.brand.nameCn || '' }}</div>
            <div>{{ scope.row.brand.nameEn || '' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="publishStatus" label="上架状态" sortable>
          <template slot-scope="scope">
            {{ scope.row.publishStatus | publishStatus }}
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="正常售價" sortable align="right" />
        <el-table-column prop="price" label="優惠價" sortable align="right" />
        <el-table-column prop="productSort" label="排序" sortable align="right" />
        <el-table-column prop="stock" label="庫存" align="right" />
        <el-table-column
          v-if="checkPer(['admin','product:edit','product:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editProduct(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog :visible="updateDeliveryVisible" center width="30%" @close="updateDeliveryVisible = false">
      <div class="dig">修改配送设置:
        <el-select
          v-model="deliverSetId"
          placeholder="请选择配送方案"
          style="width: 220px;"
        >
          <el-option
            v-for="item in deliverSet"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDeliveryVisible = false">取 消</el-button>
        <el-button type="primary" @click="fixDeliver(crud.selections)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import crudProduct from '@/api/pms/product'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import depot from '@/api/wms/depot'
import { downloadFile } from '@/utils'
import { findAll } from '@/api/sms/deliverSet'
import { getTree } from '@/api/pms/productCategory'

const defaultForm = {
  id: null,
  albumPics: null,
  brandId: null,
  nameCn: null,
  nameEn: null,
  detailTitleCn: null,
  detailTitleEn: null,
  descriptionCn: null,
  descriptionEn: null,
  detailHtml: null,
  detailMobileHtmlCn: null,
  detailMobileHtmlEn: null,
  lowStock: 0,
  newStatus: false,
  originalPrice: null,
  pic: null,
  previewStatus: false,
  price: null,
  productAttributeCategoryId: null,
  productCategoryId: null,
  promotionEndTime: null,
  promotionPerLimit: 0,
  promotionPrice: null,
  promotionStartTime: null,
  promotionType: 0,
  publishStatus: false,
  predestine: false,
  recommendStatus: false,
  sale: 0,
  productSort: 0,
  stock: 0,
  verifyStatus: false,
  weight: null
}
export default {
  name: 'Product',
  components: { pagination, crudOperation, rrOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['true_false', 'bagFeeStatus', 'publishStatus'],
  cruds() {
    return CRUD({
      title: '商品',
      url: 'product/pageList',
      sort: 'productSort:asc',
      crudMethod: { ...crudProduct },
      optShow: { del: true, reset: true },
      query: { deleteStatus: false, verifyStatus: true, publishStatus: 1 }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'product:add'],
        edit: ['admin', 'product:edit'],
        del: ['admin', 'product:del'],
        up: ['admin', 'product:up'],
        down: ['admin', 'product:down'],
        updatePack: ['admin', 'product:updatePack']
      },
      productCateOptions: [],
      deliverSet: [],
      rules: {},
      depotList: [],
      productCategoryId: [],
      updateDeliveryVisible: false,
      deliverSetId: null,
      packType: null,
      queryTypeOptions: [
        { key: 'nameCn', display_name: '中文商品名称' },
        { key: 'nameEn', display_name: '英文商品名称' }
      ],
      firstLoading: true
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    this.getProductCateList()
    this.getDeliverSet()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      if (this.firstLoading) {
        depot.getAll().then(res => {
          if (res.code === 0) {
            this.depotList = res.data
            this.crud.query.depotId = res.data[0].id
            this.crud.toQuery()
          }
        })
        this.firstLoading = false
        return false
      }
    },
    tableDeliverSet(value) {
      if (value) {
        this.deliverSet.forEach(item => {
          if (item.id === value) return (item.name)
        })
      } else {
        return ''
      }
    },
    /* 獲取配送方案 */
    getDeliverSet() {
      findAll({ deliverType: 0 }).then(res => {
        if (res.code === 0) {
          this.deliverSet = res.data
        }
      })
    },
    editProduct(data) {
      this.$router.push({ path: 'addProduct/' + (data.id || 'add') })
    },
    upOrDown(states) {
      this.$confirm(`此操作将${states ? '上架' : '下架'} 選中商品, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const productIds = this.crud.selections.map(item => { return item.id })
        crudProduct.onOffShelf({ productIds: productIds, publishStatus: states }).then(res => {
          this.$notify({
            title: res.code === 0 ? '成功' : '失敗',
            message: res.message,
            type: res.code === 0 ? 'success' : 'error'
          })
          this.crud.refresh()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    productExport() {
      crudProduct.exportProduct({ ...this.crud.query }).then(res => {
        if (res.code !== undefined && res.code !== 0) {
          this.$notify({
            title: '失敗',
            message: res.message,
            type: 'error'
          })
          return
        }
        downloadFile(res, '商品数据', 'xlsx')
      })
    },
    /* 获取商品分类树形*/
    getProductCateList() {
      getTree().then(response => {
        const list = response.data
        this.productCateOptions = []
        for (let i = 0; i < list.length; i++) {
          const children = []
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ value: list[i].children[j].id, label: list[i].children[j].label })
            }
          }
          this.productCateOptions.push({ value: list[i].id, label: list[i].label, children: children })
        }
      })
    },
    setProductCategoryId() {
      this.query.productCategoryId = this.productCategoryId[1]
      this.crud.toQuery()
    },
    fixDeliver(rows) {
      const id = rows.map(item => {
        return item.id
      })
      crudProduct.updateSetDelivery({ productIds: id, deliveryId: this.deliverSetId }).then(res => {
        this.$notify({
          title: res.code === 0 ? '成功' : '失敗',
          message: res.message,
          type: res.code === 0 ? 'success' : 'error'
        })
        if (res.code === 0) {
          this.crud.refresh()
          this.updateDeliveryVisible = false
        }
      })
    },
    sortChange(column) {
      const sortColumn = column.prop
      if (column.order === 'ascending') {
        this.crud.sort = [sortColumn + ':asc']
      }
      if (column.order === 'descending') {
        this.crud.sort = [sortColumn + ':desc']
      }
      this.crud.refresh()
    }
  }
}
</script>

<style scoped>

</style>
